package com.wowangz.cms.systemmanage.translator.service;

import static org.apache.commons.lang3.StringUtils.isBlank;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.igniterealtime.restclient.RestApiClient;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.iol.common.util.UUIDGenerator;
import com.wowangz.cms.systemmanage.translator.dao.LanguageMapper;
import com.wowangz.cms.systemmanage.translator.dao.TagsMapper;
import com.wowangz.cms.systemmanage.translator.dao.TranslatorAbilityMapper;
import com.wowangz.cms.systemmanage.translator.dao.TranslatorMapper;
import com.wowangz.cms.systemmanage.translator.dao.TranslatorTagsMapper;
import com.wowangz.cms.systemmanage.translator.pojo.ListTranslatorsResponse;
import com.wowangz.cms.systemmanage.translator.pojo.TblLanguage;
import com.wowangz.cms.systemmanage.translator.pojo.TblTags;
import com.wowangz.cms.systemmanage.translator.pojo.TblTranslator;
import com.wowangz.cms.systemmanage.translator.pojo.TblTranslatorAbility;
import com.wowangz.cms.systemmanage.translator.pojo.TblTranslatorTags;
import com.wowangz.cms.systemmanage.translator.pojo.TranslatorWithAbility;

@Service("translatorService")
public class TranslatorService {

	@Autowired
	private CoreServerAPIService coreServerAPIService;

	@Autowired
	private RestApiClient restApiClient;

	@Autowired
	private TranslatorMapper translatorMapper;

	@Autowired
	private TranslatorAbilityMapper translatorAbilityMapper;

	@Autowired
	private TranslatorTagsMapper translatorTagsMapper;

	@Autowired
	private TagsMapper tagsMapper;

	@Autowired
	private LanguageMapper languageMapper;

	/**
	 * 用户注册
	 * 
	 * @param user
	 * @param translatorTags
	 * @param ablityIds
	 * @return
	 */
	@Transactional
	public TblTranslator register(TblTranslator user, String ablityIds, String translatorTags) {
		// 校验
		String loginName = "";
		if (isBlank(user.getPhone())) {
			throw new RuntimeException("注册时用户手机号为空");
		}

		loginName = user.getPhone();

		if (isBlank(user.getPassword())) {
			throw new RuntimeException("注册时密码为空");
		}

		if (translatorMapper.uniqueByAccount(loginName) != null) {
			throw new RuntimeException(String.format("用户名[%s]已存在", loginName));
		}

		// 创建译员
		TblTranslator translator = createUser(user);
		String translatorId = translator.getId();
		// 创建译员语种
		List<TblTranslatorAbility> abilityList = null;
		if (StringUtils.isNotBlank(ablityIds)) {
			String[] abilityIdArr = ablityIds.split(",");
			List<String> tempList = new ArrayList<String>();
			tempList.addAll(Arrays.asList(abilityIdArr));
			// 译员母语能力
			tempList.add(String.valueOf(translator.getSrcLangId()));
			// 去重
			List<String> abilityIdList = new ArrayList<String>();
			Iterator<String> it = tempList.iterator();
			while (it.hasNext()) {
				String abilityId = it.next();
				if (abilityIdList.contains(abilityId)) {
					it.remove();
				} else {
					abilityIdList.add(abilityId);
				}
			}
			abilityList = new ArrayList<TblTranslatorAbility>(abilityIdList.size());
			// 译员其他外语能力
			for (String tempId : abilityIdList) {
				TblTranslatorAbility translatorAbility = new TblTranslatorAbility();
				Integer abilityId = Integer.valueOf(tempId);
				translatorAbility.setAbilityId(abilityId);
				translatorAbility.setTranslatorId(translatorId);
				translatorAbility.setCreateTime(new Date());
				abilityList.add(translatorAbility);
			}

			boolean abilityFlag = registerAbility(translatorId, abilityList);
			if (!abilityFlag) {
				throw new RuntimeException("创建译员语种异常");
			}
		}

		// 创建译员标签
		List<TblTranslatorTags> tagList = null;
		if (StringUtils.isNotBlank(translatorTags)) {
			String[] tagArr = translatorTags.split(",");
			List<String> tempTagList = new ArrayList<String>();
			tempTagList.addAll(Arrays.asList(tagArr));

			tagList = new ArrayList<TblTranslatorTags>(tempTagList.size());
			// 译员其他外语能力
			for (String translatorTag : tempTagList) {
				TblTranslatorTags tag = new TblTranslatorTags();
				tag.setTranslatorId(translatorId);
				tag.setTranslatorTag(translatorTag);
				tagList.add(tag);
			}

			boolean tagFlag = registerTag(translatorId, tagList);
			if (!tagFlag) {
				throw new RuntimeException("创建译员标签异常");
			}
		}

		// 将译员信息同步到coreserver
		coreServerAPIService.saveOrUpdateTranslator(translator, abilityList, tagList);
		return translator;
	}

	/**
	 * 创建译员
	 * 
	 * @param user
	 * @return
	 */
	private TblTranslator createUser(TblTranslator user) {
		// 补全用户信息
		user.setId(UUIDGenerator.getUUID());
		user.setDataStatus("InUse");
		Date now = new Date();
		user.setCreateTime(now);
		user.setModifyTime(now);

		// 存储用户数据
		int insNum = translatorMapper.insertSelective(user);
		if (insNum == 1) {
			return user;
		} else {
			String errDetail = String.format("插入用户[%s]结果错误[%s]", user, insNum);
			throw new RuntimeException(errDetail);
		}
	}

	/**
	 * 创建译员
	 * 
	 * @param user
	 * @return
	 */
	public boolean registerAbility(String translatoId, List<TblTranslatorAbility> abilityList) {
		// 删除原有译员能力
		TblTranslatorAbility condition = new TblTranslatorAbility();
		condition.setTranslatorId(translatoId);
		translatorAbilityMapper.delete(condition);

		boolean flag = true;
		if (null != abilityList && !abilityList.isEmpty()) {
			for (TblTranslatorAbility record : abilityList) {
				record.setId(UUIDGenerator.getUUID("A"));
				// 默认一级
				String abilityLevel = StringUtils.isBlank(record.getAbilityLevel()) ? "1" : record.getAbilityLevel();
				record.setAbilityLevel(abilityLevel);
				record.setDataStatus("InUse");
				int result = translatorAbilityMapper.insert(record);
				if (result <= 0) {
					flag = false;
				}
			}
		}
		return flag;
	}

	public boolean registerTag(String translatorId, List<TblTranslatorTags> tagList) {
		// 删除原有译员标签 再插入新的译员标签
		TblTranslatorTags condition = new TblTranslatorTags();
		condition.setTranslatorId(translatorId);
		translatorTagsMapper.delete(condition);

		boolean flag = true;
		if (null != tagList && !tagList.isEmpty()) {
			for (TblTranslatorTags record : tagList) {
				record.setId(UUIDGenerator.getUUID("T"));
				record.setCreateTime(new Date());
				int result = translatorTagsMapper.insert(record);
				if (result <= 0) {
					flag = false;
				}
			}
		}
		return flag;
	}

	/**
	 * 获取译员语种能力
	 * 
	 * @param translatorId
	 * @return
	 */
	public List<TblTranslatorAbility> getTranslatorAbility(String translatorId) {
		TblTranslatorAbility condition = new TblTranslatorAbility();
		condition.setTranslatorId(translatorId);
		condition.setDataStatus("InUse");
		List<TblTranslatorAbility> abilityList = translatorAbilityMapper.select(condition);
		return abilityList;
	}

	/**
	 * 获取译员标签
	 * 
	 * @param translatorId
	 * @return
	 */
	public List<TblTranslatorTags> getTranslatorTags(String translatorId) {
		TblTranslatorTags condition = new TblTranslatorTags();
		condition.setTranslatorId(translatorId);
		List<TblTranslatorTags> tagList = translatorTagsMapper.select(condition);
		return tagList;
	}

	/**
	 * 查询所有的tag列表
	 * 
	 * @return
	 */
	public List<TblTags> getTags() {
		return tagsMapper.selectAll();
	}

	/**
	 * 更新用户信息，不允许将已有信息清空
	 * <p />
	 * 可以更新的信息：邮箱，手机，密码，昵称，头像，母语
	 * <p />
	 * 
	 * @param user
	 * @return
	 */
	@Transactional
	public TblTranslator update(TblTranslator user, String ablityIds, String translatorTags) {
		String userId = user.getId();
		if (StringUtils.isBlank(userId)) {
			throw new RuntimeException("用户ID为空");
		}

		TblTranslator oldUser = translatorMapper.selectById(user.getId());
		if (oldUser == null) {
			throw new RuntimeException(String.format("用户[%s]不存在", user.getId()));
		}

		// 邮箱
		boolean hasUpdate = false;
		String email = user.getEmail();
		if (StringUtils.isNotBlank(email)) {
			TblTranslator otherUser = translatorMapper.uniqueByAccount(email);
			if (otherUser == null || otherUser.getId().equals(userId)) {
				oldUser.setEmail(email);
				hasUpdate = true;
			} else {
				throw new RuntimeException(String.format("用户[%s]设置的邮箱[%s]已存在", user.getId(), email));
			}
		}
		// 手机
		String phone = user.getPhone();
		if (StringUtils.isNotBlank(phone)) {
			TblTranslator otherUser = translatorMapper.uniqueByAccount(phone);
			if (otherUser == null || otherUser.getId().equals(userId)) {
				oldUser.setPhone(phone);
				hasUpdate = true;
			} else {
				throw new RuntimeException(String.format("用户[%s]设置的手机[%s]已存在", user.getId(), phone));
			}
		}
		// 昵称
		String nickName = user.getNickName();
		if (StringUtils.isNotBlank(nickName)) {
			oldUser.setNickName(nickName);
			hasUpdate = true;
		}

		// 真名
		String trueName = user.getTrueName();
		if (StringUtils.isNotBlank(trueName)) {
			oldUser.setTrueName(trueName);
			hasUpdate = true;
		}
		// 头像
		String image = user.getImage();
		if (StringUtils.isNotBlank(image)) {
			oldUser.setImage(image);
			hasUpdate = true;
		}
		// 母语
		Integer srcLangId = user.getSrcLangId();
		if (srcLangId != null) {
			oldUser.setSrcLangId(srcLangId);
			hasUpdate = true;
		}

		String password = user.getPassword();
		if (StringUtils.isNotBlank(password)) {
			oldUser.setPassword(password);
			hasUpdate = true;
		}

		String translatorType = user.getTranslatorType();
		if (StringUtils.isNotBlank(translatorType)) {
			oldUser.setTranslatorType(translatorType);
			hasUpdate = true;
		}

		String country = user.getCountry();
		if (StringUtils.isNotBlank(country)) {
			oldUser.setCountry(country);
			hasUpdate = true;
		}
		String countryCode = user.getCountryCode();
		if (StringUtils.isNotBlank(countryCode)) {
			oldUser.setCountryCode(countryCode);
			hasUpdate = true;
		}

		String onlineStatus = user.getOnlineStatus();
		if (StringUtils.isNotBlank(onlineStatus)) {
			oldUser.setOnlineStatus(onlineStatus);
			hasUpdate = true;
		}

		// 更新数据
		if (hasUpdate) {
			oldUser.setModifyTime(new Date());
			int updateNum = translatorMapper.updateByPrimaryKeySelective(oldUser);
			if (updateNum < 0) {
				String errDetail = String.format("更新用户[%s]结果错误[%s]", user, updateNum);
				throw new RuntimeException(errDetail);
			}
		}

		// 创建译员语种
		List<TblTranslatorAbility> abilityList = null;
		if (StringUtils.isNotBlank(ablityIds)) {
			String[] abilityIdArr = ablityIds.split(",");
			List<String> tempList = new ArrayList<String>();
			tempList.addAll(Arrays.asList(abilityIdArr));
			// 译员母语能力
			tempList.add(String.valueOf(oldUser.getSrcLangId()));
			// 去重
			List<String> abilityIdList = new ArrayList<String>();
			Iterator<String> it = tempList.iterator();
			while (it.hasNext()) {
				String abilityId = it.next();
				if (abilityIdList.contains(abilityId)) {
					it.remove();
				} else {
					abilityIdList.add(abilityId);
				}
			}
			abilityList = new ArrayList<TblTranslatorAbility>(abilityIdList.size());
			// 译员其他外语能力
			for (String tempId : abilityIdList) {
				TblTranslatorAbility translatorAbility = new TblTranslatorAbility();
				Integer abilityId = Integer.valueOf(tempId);
				translatorAbility.setAbilityId(abilityId);
				translatorAbility.setTranslatorId(userId);
				translatorAbility.setCreateTime(new Date());
				abilityList.add(translatorAbility);
			}

			boolean abilityFlag = registerAbility(userId, abilityList);
			if (!abilityFlag) {
				throw new RuntimeException("创建译员语种异常");
			}
		}

		// 创建译员标签
		List<TblTranslatorTags> tagList = null;
		if (StringUtils.isNotBlank(translatorTags)) {
			String[] tagArr = translatorTags.split(",");
			List<String> tempTagList = new ArrayList<String>();
			tempTagList.addAll(Arrays.asList(tagArr));

			tagList = new ArrayList<TblTranslatorTags>(tempTagList.size());
			// 译员其他外语能力
			for (String translatorTag : tempTagList) {
				TblTranslatorTags tag = new TblTranslatorTags();
				tag.setTranslatorId(userId);
				tag.setTranslatorTag(translatorTag);
				tagList.add(tag);
			}

			boolean tagFlag = registerTag(userId, tagList);
			if (!tagFlag) {
				throw new RuntimeException("创建译员标签异常");
			}
		} else {
			// 删除原有译员标签
			TblTranslatorTags condition = new TblTranslatorTags();
			condition.setTranslatorId(userId);
			translatorTagsMapper.delete(condition);
		}

		// 将译员信息同步到coreserver
		coreServerAPIService.saveOrUpdateTranslator(oldUser, abilityList, tagList);
		return oldUser;
	}

	/**
	 * 根据Id查询用户信息
	 */
	public TblTranslator getUserById(String userId) {
		return translatorMapper.selectById(userId);
	}

	public TranslatorWithAbility selectTranslatorWithProperty(String translatorId) {
		return translatorMapper.selectTranslatorWithPropertyById(translatorId);
	}

	@Transactional
	public void destroyTranslator(TblTranslator translator) {
		// 删除译员
		translatorMapper.deleteByPrimaryKey(translator.getId());
		// 删除译员语种能力
		TblTranslatorAbility ablCondition = new TblTranslatorAbility();
		ablCondition.setTranslatorId(translator.getId());
		translatorAbilityMapper.delete(ablCondition);
	}

	/**
	 * 禁用译员帐号(禁用后需要将此译员在IM上禁用强行下线)
	 * 
	 * @param translatorId
	 */
	public void block(String translatorId) {
		TblTranslator translator = translatorMapper.selectByIdIgnoreDataStatus(translatorId);
		if (null != translator) {
			TblTranslator newTranslator = new TblTranslator();
			newTranslator.setId(translator.getId());
			newTranslator.setDataStatus("BlockUp");
			newTranslator.setModifyTime(new Date());
			translatorMapper.updateByPrimaryKeySelective(newTranslator);
		}

		// 将此译员在IM上禁用并强行下线
		restApiClient.lockoutUser(translatorId);
	}

	/**
	 * 解禁译员帐号(解禁后需要将此译员在IM上解禁)
	 * 
	 * @param translatorId
	 */
	public void unblock(String translatorId) {
		TblTranslator translator = translatorMapper.selectByIdIgnoreDataStatus(translatorId);
		if (null != translator) {
			TblTranslator newTranslator = new TblTranslator();
			newTranslator.setId(translator.getId());
			newTranslator.setDataStatus("InUse");
			newTranslator.setModifyTime(new Date());
			translatorMapper.updateByPrimaryKeySelective(newTranslator);
		}

		// 将此译员在IM上解禁
		restApiClient.unlockUser(translatorId);
	}

	public List<ListTranslatorsResponse> listTranslators(Map<String, Object> map) {
		List<ListTranslatorsResponse> returnList = null;
		List<TranslatorWithAbility> translatorWithAbilityList = translatorMapper.listTranslators(map);

		if (null != translatorWithAbilityList && translatorWithAbilityList.size() > 0) {
			TblLanguage cond = new TblLanguage();
			cond.setDataStatus("InUse");
			List<TblLanguage> langList = languageMapper.select(cond);
			List<TblTags> tagList = getTags();
			returnList = new ArrayList<ListTranslatorsResponse>(translatorWithAbilityList.size());
			ListTranslatorsResponse resp = null;
			for (TranslatorWithAbility temp : translatorWithAbilityList) {
				resp = new ListTranslatorsResponse();
				resp.setEmail(temp.getEmail());
				resp.setNickName(temp.getNickName());
				resp.setPhone(temp.getPhone());
				resp.setRegType(temp.getAccountType().toString());
				resp.setThirdPartyId(temp.getThirdPartyId());
				resp.setTranslatorId(temp.getId());
				resp.setTranslatorType(temp.getTranslatorType().toString());
				resp.setTrueName(temp.getTrueName());
				resp.setDataStatus(temp.getDataStatus().toString());
				resp.setRegisterTime(new DateTime(temp.getCreateTime()).toString("yyyy-MM-dd hh:mm:ss"));
				resp.setOnlineStatus(temp.getOnlineStatus());

				// 译员语种
				List<TblTranslatorAbility> abilityList = temp.getAblityList();
				StringBuilder abilityStr = new StringBuilder("");
				for (TblTranslatorAbility ability : abilityList) {
					for (TblLanguage lang : langList) {
						if (ability.getAbilityId() == lang.getId()) {
							if (ability.getAbilityId() == temp.getSrcLangId()) {
								resp.setMontherTongue(lang.getLangNameZH());
							} else {
								abilityStr.append(lang.getLangNameZH()).append(",");
							}
						}
					}
				}
				resp.setLangAbilitys(abilityStr.toString().substring(0, abilityStr.length() - 1));

				// 译员标签
				List<TblTranslatorTags> translatorTagList = temp.getTagList();
				String tags = "";
				if (null != translatorTagList && translatorTagList.size() > 0) {
					StringBuilder tagsStr = new StringBuilder("");
					for (TblTranslatorTags translatorTag : translatorTagList) {
						for (TblTags tag : tagList) {
							if (tag.getTagName().equals(translatorTag.getTranslatorTag())) {
								tagsStr.append(tag.getTagDesc()).append(",");
							}
						}
					}
					if (tagsStr.length() > 0) {
						tags = tagsStr.substring(0, tagsStr.length() - 1);
					} else {
						tags = "";
					}
				} else {
					tags = "";
				}
				resp.setTags(tags);

				returnList.add(resp);
			}
		}

		return returnList;
	}

	public long translatorsCount(HashMap<String, Object> map) {
		return translatorMapper.translatorsCount(map);
	}

	public long translatorsCountBymybatis(HashMap<String, Object> map) {

		long count = 0;

		List<TranslatorWithAbility> list = translatorMapper.translatorsCountBymybatis(map);
		if (list != null) {
			count = list.size();
		}

		return count;
	}

}
